import config from '../config/index.js'

import md5Libs from 'js-md5'

const { version,
  os,
  env,
  dev,
  prod } = config

console.log(config)

// import md5Libs from "uview-ui/libs/function/md5";

// 加密接口参数
export function paramsSign(params) {
  const time = Date.parse(new Date()) / 1000
  // let noncestr = getRandomStr(6)
  const appid = config[env].appID;
  const app_key = config[env].appKey;
  params.encryption = config[env].encryption;

  const baseParmas = {
    appid,
    version,
    time,
    os
  }

  const map = {
    ...baseParmas,
    ...params
  }

  const sortKeys = Object.keys(map).sort()

  const strA = sortKeys.reduce((pre, key, index) => {
    if (index > sortKeys.length - 2) {
      return `${pre}${key}=${map[key]}`
    } else {
      return `${pre}${key}=${map[key]}&`
    }
  }, '')
  const strB = strA + '&key=' + app_key

  const sign = md5Libs(strB).toString()
  const upperSign = sign.toUpperCase()

  return {
    ...map,
    sign: upperSign
  }
}

function getRandomStr(len) {
  var text = ''
  var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  for (var i = 0; i < len; i++) text += possible.charAt(Math.floor(Math.random() * possible.length))
  return text
}
